package org.seata.controller;


import io.seata.spring.annotation.GlobalTransactional;
import org.seata.entity.Account;
import org.seata.service.IAccountService;
import org.seata.api.MoneyApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kingdom
 * @since 2020-10-16
 */
@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private IAccountService accountService;

    @Autowired
    private MoneyApi moneyApi;

    @PostMapping(value = "/insertAccount")
    public String insertAccount() {
        try {
            Account account = new Account();
            account.setName("king")
                    .setBalance(BigDecimal.valueOf(10000));
            accountService.save(account);
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "ERROR";
        }
    }

    @PostMapping(value = "/updateAccount")
    @GlobalTransactional(timeoutMills = 60000 * 10)
    public String updateAccount(@RequestParam(name = "accountId") String accountId,
                                @RequestParam(name = "aount") String aount) {
        Account account = accountService.getById(accountId);
        account.setBalance(account.getBalance().add(BigDecimal.valueOf(Integer.parseInt(aount))));
        accountService.updateById(account);
        moneyApi.feignUpdate(accountId, aount);
        return "SUCCESS";
    }


}

